package com.luhuiguo.sso.web.pages;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.BeanEditForm;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.internal.services.ComponentInvocationImpl;
import org.apache.tapestry5.internal.services.LinkImpl;
import org.apache.tapestry5.internal.services.OpaqueConstantTarget;
import org.apache.tapestry5.internal.services.RequestPathOptimizer;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.Response;

import com.luhuiguo.sso.web.model.LoginCredentials;

public class Login {

	@Inject
	private Request request;

	@Inject
	private Response response;

	@Inject
	private Messages messages;

	@Inject
	private RequestPathOptimizer requestPathOptimizer;

	@Property
	private LoginCredentials loginCredentials;

	@Component(id = "loginForm")
	private BeanEditForm loginForm;

	@Component(id = "username")
	private TextField usernameField;

	@OnEvent(EventConstants.ACTIVATE)
	void onActivate(String extra) {
		if (extra.equals("failed")) {
			loginForm.recordError(usernameField, messages.get("login-failed"));
		}
	}

	@OnEvent(value = Form.SUCCESS, component = "loginForm")
	Object onSuccessFromLogin() {
		Link link = new LinkImpl(response, requestPathOptimizer, null, request
				.getContextPath(), new ComponentInvocationImpl(
				new OpaqueConstantTarget("j_spring_security_check"),
				new String[0], null), false);
		link.addParameter("j_username", loginCredentials.getUsername());
		link.addParameter("j_password", loginCredentials.getPassword());
		link.addParameter("_spring_security_remember_me", Boolean
				.toString(loginCredentials.isRememberMe()));
		return link;
	}

}
